package com.ygxsk.carhome.ui.property;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.configeng.GifSizeFilter;
import com.ygxsk.carhome.configeng.Glide4Engine;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.event.RxFamilyMember;
import com.ygxsk.carhome.imagepick.ImageBean;
import com.ygxsk.carhome.imagepick.ImageShowPickerBean;
import com.ygxsk.carhome.imagepick.ImageShowPickerListener;
import com.ygxsk.carhome.imagepick.ImageShowPickerView;
import com.ygxsk.carhome.imagepick.Loader;
import com.ygxsk.carhome.listener.AuthorityCallbackListener;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.listener.RxBus;
import com.ygxsk.carhome.permission.PermissionSetting;
import com.ygxsk.carhome.permission.RuntimeRationale;
import com.ygxsk.carhome.response.CategoryAddBottomBean;
import com.ygxsk.carhome.response.CategoryAddTopBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.sys.PermissionInterceptor;
import com.ygxsk.carhome.sys.PermissionNameConvert;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.FJEditTextCountPublishTooSmall;
import com.ygxsk.carhome.views.MaxLengthWatcher;
import com.ygxsk.carhome.views.picker.CustomDatePicker;
import com.ygxsk.carhome.views.picker.DateFormatUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;
import com.zhongjh.albumcamerarecorder.album.filter.BaseFilter;
import com.zhongjh.albumcamerarecorder.listener.OnResultCallbackListener;
import com.zhongjh.albumcamerarecorder.settings.AlbumSetting;
import com.zhongjh.albumcamerarecorder.settings.CameraSetting;
import com.zhongjh.albumcamerarecorder.settings.GlobalSetting;
import com.zhongjh.albumcamerarecorder.settings.MultiMediaSetting;
import com.zhongjh.common.entity.LocalFile;
import com.zhongjh.common.entity.MultiMedia;
import com.zhongjh.common.entity.SaveStrategy;
import com.zhongjh.common.enums.MimeType;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.functions.Predicate;
import jp.wasabeef.glide.transformations.GrayscaleTransformation;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class RepairAddSubmitActivity extends ErrorActivity implements ErrorParentExtraSingle {


    interface PicChooseCallback {

        void clickCamera(int position);

        void clickCameraAndroid13(int position);

        void clickAlbum(int position, int remainNum);

        void clickAlbumAndroid13(int position, int remainNum);

    }

    /**
     * 存放相册选择列表信息
     */
    //private ArrayList<AlbumFile> mAlbumFiles;
    //========================================================================
    //装载上传图片的信息列表
    private ArrayList<ImageBean> uploadImageListPass = new ArrayList<>();

    /**
     * 上传选择分类的分类id信息
     */
    //private String repairTypeIdPass = "";

    private String houseIdPass = "";


    private String areaIdFromRoom = "";

    //========================================================================

    private PermissionSetting mSetting;

    /**
     * 该界面的所有提示通用
     */
    private AlertView mAlertView;


    /**
     * 顶部的九宫格信息
     */
    @BindView(R.id.recyclercategorytopintrans)
    RecyclerView recyclerCategoryTopintrans;

    /**
     * 底部的九宫格信息
     */
    @BindView(R.id.recyclercategorybottomintrans)
    RecyclerView recyclerCategoryBottomintrans;


    private CategoryAddTopAdapter categoryTopAdapter;
    private CategoryAddBottomAdapter categoryBottomAdapter;
    //顶部列表的数据装载
//    private ArrayList<CategoryAddTopBean> mDatasTop = new ArrayList<>();
    //底部的数据装载
//    private ArrayList<CategoryAddBottomBean> mDatasBottom = new ArrayList<>();

    //顶部列表的数据装载
    private ArrayList<CategoryAddTopBean> mDatasTop_childRepairTypeList = new ArrayList<>();
    //底部的数据装载
    private ArrayList<CategoryAddBottomBean> mDatasBottom_spaceList = new ArrayList<CategoryAddBottomBean>();


    /**
     * 界面上做提交的弹窗内容
     */
//    private MaterialDialog materialDialogUpload;

    //装载维修物品的ids,维修空间，是单选的
    private String tagmaterialIdsPass = "";

    //携带维修一级分类的分类id
    private String repairtypeID;

    //装载物品所属空间
    private ArrayList<String> tagSpaceIdsPass = new ArrayList<>();

    /**
     * 选择房间编号内容
     */
    @BindView(R.id.layoutchooseroom)
    RelativeLayout layoutchooseroom;

    /**
     * 房间编号
     */
    @BindView(R.id.textviewroom)
    TextView textViewRoom;

    /**
     * 姓名内容
     */
    @BindView(R.id.editviewname)
    EditText editViewName;

    /**
     * 联系电话信息
     */
    @BindView(R.id.textviewphonenumber)
    EditText editPhoneNumber;

    @BindView(R.id.imagevieweditbutton)
    ImageView imagevieweditbutton;  //编辑按钮内容

    //选择类别12:42 2018/11/25屏蔽掉
    //@BindView(R.id.layoutchooseleibie)
    //RelativeLayout layoutchooseleibie;

    //@BindView(R.id.textviewLeibieName)
    //TextView textviewLeibieName;//类别名称

    @BindView(R.id.edittextviewbaoxiu)
    FJEditTextCountPublishTooSmall editTextViewBaoXiu;//编辑框内容

    //------------------------------------------------------
    /**
     * 选择是否
     */
    @BindView(R.id.radiogrouphometimeinrepair)
    RadioGroup radioGroupHomeTimeInRepair;

    /**
     * 是 选择上门时间
     */
    @BindView(R.id.radiaobuttonyeschooseinrepair)
    RadioButton radiaoButtonYesChooseInRepair;

    /**
     * 否 选择上门时间
     */
    @BindView(R.id.radiaobuttonnochooseinrepair)
    RadioButton radiaoButtonNoChooseInRepair;

    /**
     * 上门时间的所有包裹内容
     */
    @BindView(R.id.laycontenthometimeall)
    RelativeLayout layContentHomeTimeAll;

    /**
     * 添加报修内容的时间的具体信息内容
     */
    @BindView(R.id.textviewhometimeinfo)
    TextView textViewHomeTimeInfo;

    //------------------------------------------------------

    /**
     * 2021-10-9 18:10:09 新添加
     */
    private String serviceTimeUpload = "";
    //------------------------------------------------------

    @BindView(R.id.it_picker_view)
    ImageShowPickerView it_picker_view;//图片选择器内容

    @BindView(R.id.buttontoadd)
    RoundTextView buttontoadd;


    private PicChooseCallback picChooseCallback = new PicChooseCallback() {
        @Override
        public void clickCamera(int position) {

            if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA)) {

                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA, new AuthorityCallbackListener() {

                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //这里两个权限组啊分开写。
                        AndPermission.with(RepairAddSubmitActivity.this)
                                .runtime()//
                                .permission(Permission.CAMERA)//仅仅是相机权限
                                .rationale(new RuntimeRationale())
                                .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
                                    @Override
                                    public void onAction(List<String> permissions) {

                                        takePhotoCamera();

                                    }
                                }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                                    @Override
                                    public void onAction(List<String> permissions) {

                                        ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);

                                        if (AndPermission.hasAlwaysDeniedPermission(RepairAddSubmitActivity.this, permissions)) {
                                            mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, RepairAddSubmitActivity.this, permissions);
                                        }

                                    }
                                }).start();

                    }
                });

            } else {

                takePhotoCamera();

            }

        }

        @Override
        public void clickCameraAndroid13(int position) {

            // TODO: 2024/1/24 11:32 android13使用的相机拍照，使用x
            if (!XXPermissions.isGranted(RepairAddSubmitActivity.this, com.hjq.permissions.Permission.CAMERA)) {

                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(RepairAddSubmitActivity.this, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);

                        XXPermissions.with(RepairAddSubmitActivity.this)
                                // 适配分区存储应该这样写
                                //.permission(Permission.Group.STORAGE)
                                // 不适配分区存储应该这样写
                                .permission(com.hjq.permissions.Permission.CAMERA)//
                                .interceptor(new PermissionInterceptor())
                                .request(new OnPermissionCallback() {

                                    @Override
                                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                        if (!allGranted) {
                                            return;
                                        }

                                        Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                PermissionNameConvert.getPermissionString(RepairAddSubmitActivity.this, permissions)));

                                        // TODO: 2024/1/24 11:49
                                        openMain(position);

                                    }
                                });

                    }
                });

            } else {

                openMain(position);

            }

        }

        @Override
        public void clickAlbum(int position, final int _remainNum) {

            if (!AndPermission.hasPermissions(mActivityInstance, Permission.CAMERA)//
                    || !AndPermission.hasPermissions(mActivityInstance, Permission.WRITE_EXTERNAL_STORAGE)//
                    || !AndPermission.hasPermissions(mActivityInstance, Permission.READ_EXTERNAL_STORAGE)) {//

                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(mActivityInstance, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_ALBUM, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //添加访问权限内容
                        AndPermission.with(RepairAddSubmitActivity.this)
                                .runtime()//
                                .permission(Permission.READ_EXTERNAL_STORAGE, //
                                        Permission.WRITE_EXTERNAL_STORAGE,//
                                        Permission.CAMERA)//
                                .rationale(new RuntimeRationale())//
                                .onGranted(new com.yanzhenjie.permission.Action<List<String>>() {
                                    @Override
                                    public void onAction(List<String> permissions) {

                                        pickPicturerAlum(_remainNum);

                                    }
                                }).onDenied(new com.yanzhenjie.permission.Action<List<String>>() {
                                    @Override
                                    public void onAction(List<String> permissions) {

                                        ToastUtils.showShort(ConstantSign.NEEDPERMISS_PHONE);

                                        if (AndPermission.hasAlwaysDeniedPermission(RepairAddSubmitActivity.this, permissions)) {
                                            mSetting.showSetting(ConstantApi.PERMISSION_NORMAL, RepairAddSubmitActivity.this, permissions);
                                        }

                                    }
                                }).start();

                    }
                });

            } else {

                pickPicturerAlum(_remainNum);

            }

        }

        @Override
        public void clickAlbumAndroid13(int position, int remainNum) {

            // TODO: 2024/1/24 11:32 android13使用的相机拍照，使用x
            if (!XXPermissions.isGranted(RepairAddSubmitActivity.this, com.hjq.permissions.Permission.CAMERA)//
                    || !XXPermissions.isGranted(RepairAddSubmitActivity.this, com.hjq.permissions.Permission.READ_MEDIA_IMAGES)) {//

                CommUtils.checkMaterialDialog(materialDialog);

                materialDialog = CommUtils.authorityRequest(RepairAddSubmitActivity.this, ConstantSign.MATERIALDIALOG_AUTHORITY_CONTENT_CAMERA, new AuthorityCallbackListener() {
                    @Override
                    public void doSomeThing() {

                        CommUtils.checkMaterialDialog(materialDialog);

                        XXPermissions.with(RepairAddSubmitActivity.this)
                                // 适配分区存储应该这样写
                                //.permission(Permission.Group.STORAGE)
                                // 不适配分区存储应该这样写
                                .permission(com.hjq.permissions.Permission.CAMERA)//
                                .permission(com.hjq.permissions.Permission.READ_MEDIA_IMAGES)//
                                .interceptor(new PermissionInterceptor())
                                .request(new OnPermissionCallback() {

                                    @Override
                                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {

                                        if (!allGranted) {
                                            return;
                                        }

                                        Toaster.show(String.format(getString(R.string.demo_obtain_permission_success_hint),
                                                PermissionNameConvert.getPermissionString(RepairAddSubmitActivity.this, permissions)));

                                        // TODO: 2024/1/24 11:49相册
                                        openMain(position);

                                    }
                                });

                    }
                });

            } else {

                openMain(position);

            }

        }

    };

    //使用相机拍照的权限；低于android13的版本适配
    private void takePhotoCamera() {

        //调用相机拍照
        Album.camera(RepairAddSubmitActivity.this)
                .image()//
                .filePath(PathUtils.getExternalAppFilesPath() + File.separator + ConstantSign.STARTWITH_REPAIR_FLAG + TimeUtils.getNowMills() + Parameterkey.jpg)//
                .onResult(new Action<String>() {//
                    @Override
                    public void onAction(@NonNull String result) {

                        //拍照路径内容
                        //Glide展示内容
                        //图片裁剪，这里暂时不裁剪。
                        //LogUtils.d("itchen----相机拍摄的路径--->" + result);
                        //2020年8月29日11:29:42 重新修改
                        //itchen----相机拍摄的路径--->/storage/emulated/0/Android/data/com.dgj.propertyred/files/repair1598671747262.jpg
                        //takePicture(result);

                        fillImagesLogic(result);

                    }

                }).onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        ToastUtils.showShort(getResources().getString(R.string.camera_cancel));
                    }
                }).start();

    }


    private Tiny.FileCompressOptions compressOptions;

    @OnClick({R.id.layoutchooseroom, //
            R.id.buttontoadd})//
    public void ClickInAdd(View view) {

        switch (view.getId()) {

            case R.id.layoutchooseroom: {//跳转到选择房间界面

                if (!DoubleClickListener.isFastDoubleClick()) {

                    //2018/11/28 想做一个效果就是只有一个房间号的时候，跳转过去那么这个房间默认就是被选中的
                    //或者说给所有已选择的都携带过去，做个标识内容。直接标识选中
                    Bundle bundle = new Bundle();

                    bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.RXBUS_PROPERTYREPAIRADD);

                    if (!TextUtils.isEmpty(houseIdPass)) {//严谨点
                        bundle.putString(ExtraKey.EXTRA_PROPERTYREPAIRADDHOUSEIDPASS, houseIdPass);
                    }

                    ActivityUtils.startActivity(bundle, SelectRoomActivity.class);

                }

                break;
            }

            //================================================================
            /*case R.id.layoutchooseleibie: {
                if (!DoubleClickListener.isFastDoubleClick()) {
                    //2018年06月25日
                    //Bundle bundle = new Bundle();
                    //是否要携带点信息？？
                    ActivityUtils.startActivity(SelectCategoryActivity.class);
                }
                break;
            }*/

            case R.id.buttontoadd: {//提交报修内容。

                if (!DoubleClickListener.isFastDoubleClick()) {

                    //测试图片地址：
                    //for (int index = 0; index < uploadImageListPass.size(); index++) {
                    //LogUtils.d("itchen--上传图片地址是" + uploadImageListPass.get(index).getImageShowPickerUrl());
                    //}

                    if (KeyboardUtils.isSoftInputVisible(RepairAddSubmitActivity.this)) {
                        KeyboardUtils.hideSoftInput(RepairAddSubmitActivity.this);
                    }


                    methodMaterialTags();//过滤维修物品
                    methodSpaceTags();//过滤所属空间

                    //数据校验
                    //房间编号：展示的仅仅是名称文本，但是实际上传houseId信息
                    String roomNumber = textViewRoom.getText().toString().trim();

                    String peopleName = editViewName.getText().toString().trim();
                    String phoneNumber = editPhoneNumber.getText().toString().trim();

                    //这个类别文字只是做空判断，id才是上传信息。
                    //String categoryName = textviewLeibieName.getText().toString().trim();
                    String repariContent = editTextViewBaoXiu.getText().toString().trim();

                    if (TextUtils.isEmpty(tagmaterialIdsPass)) {
//            method_showAlert("请选择维修物品");

                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.choose_repair_some), true);
                        mAlertView.show();

                        return;
                    }

                    if (tagSpaceIdsPass.isEmpty()) {
//            method_showAlert("请选择物品所属空间");
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_spaces_items), true);
                        mAlertView.show();
                        return;
                    }


                    if (TextUtils.isEmpty(roomNumber)) {
//            method_showAlert("请选择房间号");
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_choose_home_number), true);
                        mAlertView.show();
                        return;
                    }

                    if (TextUtils.isEmpty(peopleName)) {
//            method_showAlert("请填写姓名");
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_person_name), true);
                        mAlertView.show();
                        return;
                    }

                    if (TextUtils.isEmpty(phoneNumber)) {
//            method_showAlert("请填写手机号");
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_person_phone), true);
                        mAlertView.show();
                        return;
                    }

                    if (!RegexUtils.isMobileSimple(phoneNumber)) {
//            method_showAlert("电话格式不对");
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_right_phone), true);
                        mAlertView.show();
                        return;
                    }

//        if (!RegexUtils.isMobileExact(phoneNumber)) {//精确验证手机号
//            method_showAlert("请输入有效手机号");
//        CommUtils.checkDialog(mAlertView);
//        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_sure_phone), true);
//        mAlertView.show();
//            return;
//        }


                    if (TextUtils.isEmpty(repariContent)) {
//            method_showAlert("请填写报修内容");
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.please_input_repair_content), true);
                        mAlertView.show();

                        return;
                    }

                    CommUtils.checkDialog(mAlertView);

                    //2020年8月26日09:48:42添加二次弹窗确认:这个版本的不要提示标题
                    mAlertView = new AlertView(getResources().getString(R.string.clearaddorsubmitsuretitletips),//提示
                            getResources().getString(R.string.clearaddorsubmitsuremessage),//确定提交吗？
                            getResources().getString(R.string.clearcachecancel), //取消
                            new String[]{getResources().getString(R.string.clearaddorsubmitsure)},//提交
                            null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                //upload
                                method_uploadRepairInfo(uploadImageListPass, peopleName, phoneNumber, repariContent);

                                //这里做个 rxjava的重试提交，防止提交失败
//                                mCompositeDisposable.add(Observable.just(0)//
//                                        //.retry(3)//重试3次吧，
//                                        .subscribeOn(AndroidSchedulers.mainThread())//AndroidSchedulers.mainThread()
//                                        .observeOn(AndroidSchedulers.mainThread())//
//                                        .subscribe(new Consumer<Integer>() {
//                                            @Override
//                                            public void accept(Integer integer) throws Exception {
//
//                                                //upload
////                                                method_uploadRepairInfo(uploadImageListPass);
//
//                                            }
//                                        }, new Consumer<Throwable>() {
//                                            @Override
//                                            public void accept(Throwable throwable) throws Exception {
//
//                                                //LogUtils.e("itchen---->报错了---->" + throwable.getMessage());
//                                            }
//                                        }));

                            }

                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }

                break;
            }
            default:
                break;
        }
    }

    private GlobalSetting mGlobalSetting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
                        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        mActivityInstance = this;

        if (mDatasTop_childRepairTypeList == null) {
            mDatasTop_childRepairTypeList = new ArrayList<>();
        }

        if (mDatasBottom_spaceList == null) {
            mDatasBottom_spaceList = new ArrayList<>();
        }

        //mRationale = new DefaultRationale();
        mSetting = new PermissionSetting(this);

        processExtraData();

        initViews();

        mCompositeDisposable.add(RxBus.getInstance().toObserverable(RxFamilyMember.class)//
                .subscribeOn(AndroidSchedulers.mainThread())//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Consumer<RxFamilyMember>() {
                    @Override
                    public void accept(RxFamilyMember rxFamilyMember) throws Throwable {

                        if (rxFamilyMember.getMessage() == ExtraValue.RXBUS_PROPERTYREPAIRADD) {

                            if (textViewRoom != null) {

                                //填充最新的房间内容
                                textViewRoom.post(new Runnable() {

                                    @Override
                                    public void run() {

                                        //String communityName = rxFamilyMember.getRoomBean().getCommunityName();
                                        houseIdPass = rxFamilyMember.getRoomBean().getHouseId();
                                        areaIdFromRoom = rxFamilyMember.getRoomBean().getAreaId();

                                        StringBuffer stringBuffer = new StringBuffer();
                                        //第一句早期注释掉
                                        //stringBuffer.append(rxFamilyMember.getRoomBean().getCommunityName());
                                        if (!TextUtils.isEmpty(rxFamilyMember.getRoomBean().getAreaName())) {
                                            stringBuffer.append(rxFamilyMember.getRoomBean().getAreaName());
                                            stringBuffer.append("   ");//
                                        }

                                        if (!TextUtils.isEmpty(rxFamilyMember.getRoomBean().getHouseNo())) {
                                            stringBuffer.append(rxFamilyMember.getRoomBean().getHouseNo());
                                        }

                                        textViewRoom.setText(stringBuffer.toString());

                                    }
                                });
                            }
                        }

                        //2018/11/25 更改需求，只有一个房间的时候直接填充房间编号信息。
                        /*else if (rxFamilyMember.getMessage() == ConstantApi.RXBUS_PROPERTYREPAIR_CATEGORY) {
                        //关于RxFamilyMember这个在此处第一次做了扩展

                            //从报修类别跳转过来到添加报修界面。
                            if (textviewLeibieName != null) {

                                textviewLeibieName.post(new Runnable() {
                                    @Override
                                    public void run() {

                                        repairTypeIdPass = rxFamilyMember.getInfoId();//携带的id信息，这里携带的是报修类别id

                                        CommUtils.setText(textviewLeibieName, rxFamilyMember.getInfoContent());

                                    }
                                });
                            }
                        }*/

                    }
                }));


        //做图片压缩的配置。
        compressOptions = new Tiny.FileCompressOptions();
        compressOptions.config = Bitmap.Config.ARGB_8888;
        //这种是原图 会导致 服务器端 压缩的特别厉害 例如
        //http://222.222.17.184:8881/resource/image/repairImg/20200901/2020090109140499089232_500x500.jpg
        //http://222.222.17.184:8881/resource/image/repairImg/20200901/2020090109140535411976_500x500.jpg
        //http://222.222.17.184:8881/resource/image/repairImg/20200901/2020090109140557140787_500x500.jpg
        //compressOptions.quality=100;

        //修复软键盘顶起底部导航，放开之后是解决了问题，但是同时也顶起了底部的【提交报修】按钮。
        //KeyboardUtils.fixAndroidBug5497(RepairAddSubmitActivity.this);

        gainDatas();

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_repair_add_submit;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        toolbarHelper.setTitle(getString(R.string.title_repair_add));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(true, 1, "历史记录", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //这个也是更多，跳转到选项卡列表页，携带搜索？
//                Bundle extra_bundle = new Bundle();
//                //这里的更多是单个人的更多？还是包裹所有人的？
////                ActivityUtils.startActivity(SmartGoOutActivity.this, CardDistHistoryActivity.class);
////                ActivityUtils.startActivity(SmartGoOutActivity.this, SmartGoRecordHistoryActivity.class);
//                ActivityUtils.startActivity(SmartGoOutActivity.this, SmartGoSumHistoryActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        //

    }

    @Override
    protected void initViews() {

        //填充九宫格内容--顶部九宫格
        GridLayoutManager layoutManagerTop = new GridLayoutManager(this, 4);
        //layoutManagerTop.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerCategoryTopintrans.setLayoutManager(layoutManagerTop);

        //底部适配器的列表信息
        GridLayoutManager layoutManagerBottom = new GridLayoutManager(this, 4);
        //layoutManagerBottom.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerCategoryBottomintrans.setLayoutManager(layoutManagerBottom);

        //topadapter
        categoryTopAdapter = new CategoryAddTopAdapter(R.layout.categorybottomtransadapter, mDatasTop_childRepairTypeList);
        //减小抖动。
        categoryTopAdapter.setHasStableIds(true);
        recyclerCategoryTopintrans.setAdapter(categoryTopAdapter);

        categoryTopAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //第一种 单个刷新 图片
                //第二种 整体刷新 图片
                //第三种方式刷新 记录上次是红色的index 然后紧紧刷新上一次和这次点中的。
                int positionLastChecked = 0;

                //关闭软键盘
                if (KeyboardUtils.isSoftInputVisible(RepairAddSubmitActivity.this)) {
                    KeyboardUtils.hideSoftInput(RepairAddSubmitActivity.this);
                }

                //2019年10月09日，优化一次，如果已经是选中状态的，让代码返回
                if (((CategoryAddTopBean) adapter.getItem(position)).isChecked()) {
                    //LogUtils.d("itchen---已经是选中状态，代码返回");
                    return;
                }

                for (int indexLastCheck = 0; indexLastCheck < mDatasTop_childRepairTypeList.size(); indexLastCheck++) {

                    if (mDatasTop_childRepairTypeList.get(indexLastCheck).isChecked()) {
                        //LogUtils.d("itchen---上次选中的位置是：=>"+indexLastCheck);
                        positionLastChecked = indexLastCheck;
                    }

                }

                //=========================================================
                //控制单选
                for (int index = 0; index < mDatasTop_childRepairTypeList.size(); index++) {

                    if (index == position) {

                        mDatasTop_childRepairTypeList.get(index).setChecked(true);

                        if (categoryTopAdapter != null) {
                            categoryTopAdapter.notifyItemChanged(position);
                        }

                    } else {

                        mDatasTop_childRepairTypeList.get(index).setChecked(false);

                        //if (categoryTopAdapter != null) {
                        //categoryTopAdapter.notifyItemChanged(index);
                        //}
                    }
                }

                //这种刷新本次点中和上次选中的位置记录，效果更好，比第二种整体刷新体验更优
                if (categoryTopAdapter != null) {
                    categoryTopAdapter.notifyItemChanged(positionLastChecked);
                }


                //if (categoryTopAdapter != null) {
                //2019/10/09 改用全部统一刷新一次,也会导致选中的图片有轻微的抖动。
                //categoryTopAdapter.notifyDataSetChanged();
                //}

                //=========================================================
            }
        });


        categoryBottomAdapter = new CategoryAddBottomAdapter(R.layout.categorytoptransadapter, mDatasBottom_spaceList);
        categoryBottomAdapter.setHasStableIds(true);
        recyclerCategoryBottomintrans.setAdapter(categoryBottomAdapter);

        categoryBottomAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //关闭软键盘
                if (KeyboardUtils.isSoftInputVisible(RepairAddSubmitActivity.this)) {
                    KeyboardUtils.hideSoftInput(RepairAddSubmitActivity.this);
                }

                CategoryAddBottomBean categoryAddBottomBean = (CategoryAddBottomBean) adapter.getItem(position);

                switch (view.getId()) {

                    case R.id.textviewtagevabottom: {

                        /*for (int index = 0; index < mDatasTop.size(); index++) {
                            if (index == position) {
                                mDatasBottom.get(index).setChecked(true);
                            } else {
                                mDatasBottom.get(index).setChecked(false);
                            }
                        }*/

                        if (categoryAddBottomBean.isChecked()) {//如果被选中就反选
                            categoryAddBottomBean.setChecked(false);
                        } else {
                            categoryAddBottomBean.setChecked(true);
                        }

                        if (categoryBottomAdapter != null) {
                            categoryBottomAdapter.notifyDataSetChanged();
                        }

                        break;
                    }

                    default:
                        break;
                }

            }
        });

        //===========================================================================================

        //===========================================================================================


        //2018年06月06日，填充tureName信息内容
        editViewName.setText(mSession.getTrueName());

        //填充手机号等默认填充信息
        editPhoneNumber.setText(mSession.getUserPhone());

        //edittextviewbaoxiu.getEditText().setOnTouchListener(this);
        editViewName.addTextChangedListener(new MaxLengthWatcher(ConstantApi.MAXLENEDITTEXT, editViewName, "文本不能超出12个字"));

        //===================================================================================
        //图片选择器内容
        it_picker_view.setImageLoaderInterface(new Loader());
        it_picker_view.setShowAnim(true);
        it_picker_view.setmAddLabel(R.drawable.addpublish);

        it_picker_view.setPickerListener(new ImageShowPickerListener() {

            @Override
            public void addOnClickListener(final int remainNum) {//参数是剩余的，残留的，有待

                //LogUtils.d("itchen---添加图片内容remainNum==" + remainNum);

                CommUtils.checkDialog(mAlertView);

                //弹窗从相机或者相册选择
                mAlertView = new AlertView(getResources().getString(R.string.title_idcard_pickphoto),//选择图片
                        null,//
                        getResources().getString(R.string.cancel),//取消
                        null,//
                        new String[]{getResources().getString(R.string.upload_idcard_takephoto),//拍照
                                getResources().getString(R.string.upload_idcard_pickphoto)},//从相册中选择
                        RepairAddSubmitActivity.this,//
                        AlertView.Style.ActionSheet,//
                        new com.ygxsk.carhome.alertview.OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position == 0) {//相机

                                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                        if (picChooseCallback != null) {
                                            picChooseCallback.clickCamera(0);
                                        }

                                    } else {

                                        if (picChooseCallback != null) {
                                            picChooseCallback.clickCameraAndroid13(0);
                                        }

                                    }

                                } else if (position == 1) {//相册选择

                                    //Permission.READ_EXTERNAL_STORAGE,//
                                    //Permission.WRITE_EXTERNAL_STORAGE

                                    //如果Android版本大于13，还有一套逻辑。

                                    try {
                                        //do

                                        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {

                                            if (picChooseCallback != null) {
                                                picChooseCallback.clickAlbum(1, remainNum);
                                            }

                                        } else {

                                            if (picChooseCallback != null) {
                                                picChooseCallback.clickAlbumAndroid13(1, remainNum);
                                            }

                                        }

                                    } catch (Exception e) {
                                        //catch
                                        e.printStackTrace();
                                    }

                                }
                            }
                        });

                mAlertView.setCancelable(true)//
                        .show();//

            }

            @Override
            public void picOnClickListener(List<ImageShowPickerBean> list, int position, int remainNum) {

                ArrayList<String> tempList = new ArrayList<>();

                for (ImageShowPickerBean imagepick : list) {
                    tempList.add(imagepick.getImageShowPickerUrl());
                }

                //这个是点击图片的内容。这里使用浏览图片
                Album.gallery(RepairAddSubmitActivity.this)
                        .checkedList(tempList)
                        //.navigationAlpha(80)
                        .checkable(false)//是否出现选择对勾内容
                        .currentPosition(position)//2018  对应位置错乱 2020-5-23 11:56:15不知是否有问题 反正放开了
                        .widget(//
                                Widget.newLightBuilder(RepairAddSubmitActivity.this)
                                        .title("图片查看")//
                                        .toolBarColor(Color.WHITE)
                                        .statusBarColor(Color.WHITE)
                                        .build()
                        )
                        .onResult(new Action<ArrayList<String>>() {
                            @Override
                            public void onAction(@NonNull ArrayList<String> result) {
                                //  If it is optional, here you can accept the results of user selection.

                            }

                        })
                        .start();


            }

            @Override
            public void delOnClickListener(int position, int remainNum) {//这个是删除了那张图片

                if (!uploadImageListPass.isEmpty()) {
                    uploadImageListPass.remove(position);
                }

            }

            @Override
            public void longClickListener(List<ImageShowPickerBean> list, int position, int remainNum) {

                //添加长按内容

            }
        });

        it_picker_view.show();//展示的:确定要先添加事件之后再展示？

        //====================================================================================================

        //====================================================================================================
        //上门时间：
        //是点击弹窗时间选择器的
        //开始默认时候是选择否的
        if (radiaoButtonYesChooseInRepair != null) {
            radiaoButtonYesChooseInRepair.setChecked(false);
            radiaoButtonYesChooseInRepair.setTextColor(ColorUtils.getColor(R.color.dark));
        }

        if (radiaoButtonNoChooseInRepair != null) {
            radiaoButtonNoChooseInRepair.setChecked(true);
            radiaoButtonNoChooseInRepair.setTextColor(ColorUtils.getColor(R.color.redcomm));
        }

        radioGroupHomeTimeInRepair.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.radiaobuttonyeschooseinrepair: {//选择是添加上门时间

                        Delivery.getInstance().post(new Runnable() {

                            @Override
                            public void run() {

                                if (radiaoButtonYesChooseInRepair != null) {
                                    radiaoButtonYesChooseInRepair.setTextColor(ColorUtils.getColor(R.color.redcomm));
                                }

                                if (radiaoButtonNoChooseInRepair != null) {
                                    radiaoButtonNoChooseInRepair.setTextColor(ColorUtils.getColor(R.color.dark));
                                }

                                CommUtils.setViewVisible(layContentHomeTimeAll);

                                if (layContentHomeTimeAll != null) {

                                    layContentHomeTimeAll.setOnClickListener(new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {

                                            initTimerPicker();

                                        }
                                    });

                                }
                            }
                        });

                        break;
                    }


                    case R.id.radiaobuttonnochooseinrepair: {//选择否 不添加上门时间

                        Delivery.getInstance().post(new Runnable() {

                            @Override
                            public void run() {

                                if (radiaoButtonNoChooseInRepair != null) {
                                    radiaoButtonNoChooseInRepair.setTextColor(ColorUtils.getColor(R.color.redcomm));
                                }

                                if (radiaoButtonYesChooseInRepair != null) {
                                    radiaoButtonYesChooseInRepair.setTextColor(ColorUtils.getColor(R.color.dark));
                                }

                                CommUtils.setViewGone(layContentHomeTimeAll);

                            }
                        });

                        break;
                    }

                    default:
                        break;
                }

            }
        });

        //====================================================================================================


    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {


//            if ((mDatasTop != null) && (!mDatasTop.isEmpty())) {
//                mDatasTop.clear();
//            }
//
//            if ((mDatasBottom != null) && (!mDatasBottom.isEmpty())) {
//                mDatasBottom.clear();
//            }
//
//            getServerDatas();

        } else {
            //后期再添加
            netWorkError();
        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDatasTop_childRepairTypeList != null) {
            mDatasTop_childRepairTypeList.clear();
        }

        if (mDatasBottom_spaceList != null) {
            mDatasBottom_spaceList.clear();
        }

        //====================================================================
        //清空顶部分类选择
        if ((mDatasTop_childRepairTypeList != null) && (!mDatasTop_childRepairTypeList.isEmpty())) {
            mDatasTop_childRepairTypeList.clear();
        }

        if (categoryTopAdapter != null) {
            categoryTopAdapter = null;
        }

        //清空底部分类选择
        if ((mDatasBottom_spaceList != null) && (!mDatasBottom_spaceList.isEmpty())) {
            mDatasBottom_spaceList.clear();
        }

        if (categoryBottomAdapter != null) {
            categoryBottomAdapter = null;
        }

        //房间编号清空
        if (textViewRoom != null) {
            if (!TextUtils.isEmpty(textViewRoom.getText().toString().trim())) {
                textViewRoom.setText("");
                //LogUtils.d("itchen---清空房间号");
            }
        }

        //清空报修内容
        if (editTextViewBaoXiu != null) {
            if (!TextUtils.isEmpty(editTextViewBaoXiu.getText().toString().trim())) {
                editTextViewBaoXiu.setText("");
                //LogUtils.d("itchen---清空房报修内容");
            }
        }

        //清空报修图片内容
        if (!uploadImageListPass.isEmpty()) {
            uploadImageListPass.clear();
        }

        //====================================================================
        if (!TextUtils.isEmpty(repairtypeID)) {
            repairtypeID = "";//reset
        }

        if (!TextUtils.isEmpty(houseIdPass)) {
            houseIdPass = "";
        }

        if (!TextUtils.isEmpty(areaIdFromRoom)) {
            areaIdFromRoom = "";
        }

        //清空页面数据，避免仍然有携带。
        if (mSetting != null) {
            mSetting = null;
        }

        /*if (mRationale != null) {
            mRationale = null;
        }*/

//        if (mAlertView != null) {
//
//            if (mAlertView.isShowing()) {
//                mAlertView.dismiss();
//                mAlertView = null;
//            }
//
//        }

//        if (mCompositeDisposable != null) {
//            mCompositeDisposable.clear();
//        }

        if (mGlobalSetting != null) {
            mGlobalSetting.onDestroy();
        }

    }

    private void fillImagesLogic(final String _imagePath) {

        Tiny.getInstance().source(_imagePath).asFile().withOptions(compressOptions).compress(new FileCallback() {

            @Override
            public void callback(boolean isSuccess, String outfile, Throwable t) {

                if (!isSuccess) {//压缩失败就上传原图即可。
                    //LogUtils.d("itchen--有压缩失败-" + t.getMessage());
                    //return;

                    ImageBean imageBean = new ImageBean(_imagePath);

                    if (it_picker_view != null) {
                        it_picker_view.addData(imageBean);
                    }

                    uploadImageListPass.add(imageBean);


                } else {//图片压缩成功，上传压缩图

                    //File file = new File(outfile);
                    //setupCompressInfo(outfile, file.length());
                    //LogUtils.d("itchen---图片压缩成功=>"+outfile);
                    //itchen---图片压缩成功=>/storage/emulated/0/Android/data/com.dgj.propertyowner/tiny/tiny-40-2018-04-04-14-05-45.jpg
                    ImageBean imageBean = new ImageBean(outfile);
                    if (it_picker_view != null) {
                        it_picker_view.addData(imageBean);
                    }
                    uploadImageListPass.add(imageBean);

                }

            }
        });


        //原始未添加压缩的图片代码
        /*ImageBean imageBean = new ImageBean(imagePath);
        it_picker_vi.addData(imageBean);
        uploadImageListPass.add(imageBean);*/
    }

    //===============================================================================================================
    public void pickPicturerAlum(int _remainNum) {

        //从相册里选择图片
        //调用相册选择
        //调用相册选择
        Album.image(RepairAddSubmitActivity.this)
                .multipleChoice()//可以多选
                //.singleChoice()//
                .camera(true)//
                .columnCount(3)//
                .selectCount(_remainNum + 1)//最多只能选择1张照片.不然导致我的相册出bug.这里需要重新整改。
                //.checkedList(mAlbumFiles)//多选的时候避免重复选择
                .widget(Widget.newLightBuilder(RepairAddSubmitActivity.this)//自定义的界面可以不要
                        .title("选择图库")//
                        .statusBarColor(Color.WHITE)//状态栏颜色。
                        .toolBarColor(Color.WHITE)//Toolbar颜色。
                        .mediaItemCheckSelector(Color.BLUE, Color.RED)//图片或者视频选择框的选择器。
                        .bucketItemCheckSelector(Color.BLUE, Color.WHITE)//切换文件夹时文件夹选择框的选择器
                        .buttonStyle(Widget.ButtonStyle.newLightBuilder(RepairAddSubmitActivity.this)//
                                .setButtonSelector(Color.BLUE, Color.WHITE)//
                                .build()).build())//

                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {


                        //2018/11/30 原始代码发现该处并没用到
                        //mAlbumFiles = result;

                        /*ArrayList<String> pathStringList = new ArrayList<>();
                        for (AlbumFile albumFile:result) {
                            pathStringList.add(albumFile.getPath());
                        }
                        takePicture(pathStringList);//图片路径内容
                        */
                        //==========================================================================
                        //这个列表 要单独划开，因为上传的时候 要整体上传的。
                        // 准备采用。图片压缩。

                        //2018年03月14日。原始代码。
                        for (int index = 0; index < result.size(); index++) {

                            fillImagesLogic(result.get(index).getPath());
                            //LogUtils.d("itchen----->" + result.get(index).getPath());

                        }
                    }

                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
//                        CommUtils.displayToastShort(RepairAddSubmitActivity.this, "取消了");
                        ToastUtils.showShort(getResources().getString(R.string.camera_cancel));
                    }

                })
                .start();

    }

    //提交报修内容的接口。
    private void method_uploadRepairInfo(ArrayList<ImageBean> _uploadImageListPass,//
                                         String _inputPersonName_employeeOrOwner,//
                                         String _phoneNumber,//报修人手机号
                                         String _repairContent) {//报修人投诉内容


        //携带多张图片
        //form表单提交
        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()//
                .setType(MultipartBody.FORM);//

        //不是做上传，是为了做日志上传用的
        ArrayList<String> addLogList = new ArrayList<>();

        //2020年8月26日09:52:54 这里如果不判断的话，如果是空的，可能会导致rxjava直接失败
        if (_uploadImageListPass != null && !_uploadImageListPass.isEmpty()) {

            for (ImageBean imageBean : _uploadImageListPass) {

                String imageLocalPath = imageBean.getImageShowPickerUrl();
                //LogUtils.d("itchen---imagePathUpLoad==" + imagePath);

                if (!TextUtils.isEmpty(imageLocalPath)) {

                    File file = new File(imageLocalPath);
                    multipartBodyBuilder.addFormDataPart(Parameterkey.fileList, file.getName(),//
                            RequestBody.create(file, MediaType.parse(ApiService.MEDIATYPE_IMAGE_JPG)));//

                    addLogList.add(imageLocalPath);

                } else {
                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "itchen---->添加报修的图片地址 fileSingleUpLoadFiles_upLoad_hashMap 是空的");
                }

            }
        }


        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());
        map.put(Parameterkey.areaId, areaIdFromRoom);
        map.put(Parameterkey.userName, _inputPersonName_employeeOrOwner);
        map.put(Parameterkey.userPhone, _phoneNumber);
        map.put(Parameterkey.content, _repairContent);
        map.put(Parameterkey.houseId, houseIdPass);
        map.put(Parameterkey.repairTypeId, tagmaterialIdsPass);
        map.put(Parameterkey.serviceTime, serviceTimeUpload);
        map.put(Parameterkey.spaceIds, tagSpaceIdsPass.toString().replace("[", "").replace("]", ""));

        multipartBodyBuilder.addFormDataPart(Parameterkey.shopInfoId, mSession.getShopInfoId());
        multipartBodyBuilder.addFormDataPart(Parameterkey.areaId, areaIdFromRoom);
        multipartBodyBuilder.addFormDataPart(Parameterkey.userName, _inputPersonName_employeeOrOwner);
        multipartBodyBuilder.addFormDataPart(Parameterkey.userPhone, _phoneNumber);
        multipartBodyBuilder.addFormDataPart(Parameterkey.content, _repairContent);
        multipartBodyBuilder.addFormDataPart(Parameterkey.houseId, houseIdPass);
        multipartBodyBuilder.addFormDataPart(Parameterkey.repairTypeId, tagmaterialIdsPass);
        multipartBodyBuilder.addFormDataPart(Parameterkey.serviceTime, serviceTimeUpload);
        multipartBodyBuilder.addFormDataPart(Parameterkey.spaceIds, tagSpaceIdsPass.toString().replace("[", "").replace("]", ""));

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_ADDREPAIR_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.addRepair_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                //.saveOutdoorCertificate(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .addRepair(multipartBodyBuilder.build())
                .compose(RepairAddSubmitActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        method_create_materialDialog(mActivityInstance, ConstantSign.TIPS_SUBMIT);
                    }
                }).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        CommUtils.checkMaterialDialog(materialDialog);

                        methodSubmitSuccess(RepairAddSubmitActivity.this, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                mCompositeDisposable.add(Observable.just(1, 2, 3)
                                        .subscribeOn(AndroidSchedulers.mainThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .compose(RepairAddSubmitActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(Integer integer) throws Throwable {

                                                if (integer == 1) {

                                                    //2018/11/25 不做通知了
                                                    //这里通知了列表刷新之后,那么添加报修成功结果页则杀死结果页当前界面即可。也是最新数据
                                                    //EventBus.getDefault().post(new EventRepair(ConstantApi.EVENTBUS_REPAIR_ADDSUCCESS));

                                                    if (!TextUtils.isEmpty(stringValue)) {//stringValue 其实是这条维修的id信息，携带到下一个页面去做查询详情。

                                                        //直接跳转到了报修详情界面
                                                        Bundle bundle = new Bundle();
                                                        //2022-2-10 16:17:18 这里可以省略
                                                        //bundle.putInt(ConstantApi.EXTRA_JUMPFROM_WHERE, ConstantApi.VALUE_JUMPFROM_PROPERTY_ACTIVITY);
                                                        bundle.putString(ExtraKey.EXTRA_REPAIR_REPAIRID, stringValue);
                                                        //携带商品整个实体？
                                                        ActivityUtils.startActivity(bundle, RepairdDetailActivity.class);

                                                    } else {

                                                        ToastUtils.showShort(getResources().getString(R.string.http_exception_network));
                                                    }


                                                } else if (integer == 2) {

                                                    // TODO: 2023/12/28 14:08 要不要主动删除？会不会产生问题？
                                                    //中间删除上传图片信息的操作
//                                                    methodDeleteImageFile();

                                                } else if (integer == 3) {

                                                    //中间删除上传图片信息的操作

                                                    //methodResult(singleObjectTools.getData());
                                                    //退出该界面
                                                    methodBack();
                                                }


                                            }
                                        }));

                            }
                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });


    }

    //检查维修物品标签内容,维修空间的过滤 底部九宫格的过滤。
    private void methodSpaceTags() {

        //--第一种的原始方式-可用---------------------------------------------------------------------------
        /*if (!tagSpaceIdsPass.isEmpty()) {
            tagSpaceIdsPass.clear();
        }

        for (CategoryAddBottomBean categoryAddBottomBean : mDatasBottom) {
            if (categoryAddBottomBean.isChecked()) {
                tagSpaceIdsPass.add(categoryAddBottomBean.getSpaceId());
            }
        }*/
        //------------------------------------------------------------------------------
        //第二种使用2019/3/4 星期一 16:51:22 做测试的改造
        Observable.create(new ObservableOnSubscribe<CategoryAddBottomBean>() {


            @Override
            public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<CategoryAddBottomBean> emitter) throws Throwable {
                for (CategoryAddBottomBean categoryAddBottomBean : mDatasBottom_spaceList) {
                    //LogUtils.d("itchen--emitter---发送了->" + categoryAddBottomBean.getSpaceKind() + "id==>" + categoryAddBottomBean.getSpaceId());
                    emitter.onNext(categoryAddBottomBean);
                }

                //LogUtils.d("itchen---->即将发射--onComplete");

                emitter.onComplete();
            }
        }).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Throwable {

                //LogUtils.d("itchen--doOnSubscribe---在执行订阅之前先处理->" + disposable.isDisposed());
                if (!tagSpaceIdsPass.isEmpty()) {
                    tagSpaceIdsPass.clear();
                }

            }
        }).filter(new Predicate<CategoryAddBottomBean>() {
            @Override
            public boolean test(CategoryAddBottomBean categoryAddBottomBean) throws Throwable {

                //LogUtils.d("itchen--filter---test--测试了--->" + categoryAddBottomBean.getSpaceKind() + "id==>" + categoryAddBottomBean.getSpaceId());
                return categoryAddBottomBean.isChecked();
            }
        }).subscribe(new Consumer<CategoryAddBottomBean>() {
            @Override
            public void accept(CategoryAddBottomBean categoryAddBottomBean) throws Throwable {
                //LogUtils.d("itchen--subscribe---accept--最终符合条件的--->" + categoryAddBottomBean.getSpaceKind() + "id==>" + categoryAddBottomBean.getSpaceId());
                tagSpaceIdsPass.add(categoryAddBottomBean.getSpaceId());
            }
        });

    }

    /**
     * 检查物品所属空间标签
     */
    private void methodMaterialTags() {


        //第一种方式 可行 ，后来用的RxJva改造的
        //首先重置一下。
        /*tagmaterialIdsPass = "";
        for (CategoryAddTopBean categoryAddTopBean : mDatasTop) {
            if (categoryAddTopBean.isChecked()) {
                tagmaterialIdsPass = categoryAddTopBean.getRepairTypeId();
            }
        }*/

        //第二种使用RxJava改造内容, 亲测可行
        //2019/3/4 星期一 16:51:22
        Observable.create(new ObservableOnSubscribe<CategoryAddTopBean>() {
                    @Override
                    public void subscribe(@io.reactivex.rxjava3.annotations.NonNull ObservableEmitter<CategoryAddTopBean> emitter) throws Throwable {

                        for (CategoryAddTopBean categoryAddTopBean : mDatasTop_childRepairTypeList) {

                            //LogUtils.d("itchen---emitter---->" + categoryAddTopBean.getTypeName() + "--id-->" + categoryAddTopBean.getRepairTypeId());
                            emitter.onNext(categoryAddTopBean);

                        }

                        //执行完毕上边的循环之后
                        //LogUtils.d("itchen---即将发射--->onComplete");
                        emitter.onComplete();

                    }
                }).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        //LogUtils.d("itchen----doOnSubscribe 在执行订阅过滤之前先重置数据---tagmaterialIdsPass-->");
                        //订阅之前就重置一遍tagmaterialIdsPass 的原始状态
                        tagmaterialIdsPass = "";

                    }
                }).compose(RepairAddSubmitActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .filter(new Predicate<CategoryAddTopBean>() {
                    @Override
                    public boolean test(CategoryAddTopBean categoryAddTopBean) throws Throwable {

                        //LogUtils.d("itchen---filter-test--->" + categoryAddTopBean.getTypeName() + "--id-->" + categoryAddTopBean.getRepairTypeId());

                        return categoryAddTopBean.isChecked();//将符合条件的
                    }
                }).subscribe(new Consumer<CategoryAddTopBean>() {
                    @Override
                    public void accept(CategoryAddTopBean categoryAddTopBean) throws Throwable {
                        //LogUtils.d("itchen---accept--最终符合条件的--->" + categoryAddTopBean.getTypeName() + "--id-->" + categoryAddTopBean.getRepairTypeId());

                        tagmaterialIdsPass = categoryAddTopBean.getRepairTypeId();
                    }
                });

    }


    @Override
    public void processExtraData() {

        if (mDatasTop_childRepairTypeList != null) {
            mDatasTop_childRepairTypeList.clear();
        }

        if (mDatasBottom_spaceList != null) {
            mDatasBottom_spaceList.clear();
        }

        Bundle bundle = this.getIntent().getExtras();

        //use the data received here
        if (bundle != null) {

            //处理携带data
            repairtypeID = bundle.getString(ExtraKey.EXTRA_REPAIRTYPEID);

            //携带维修位置
            ArrayList<CategoryAddTopBean> extra_childRepairTypeList = bundle.getParcelableArrayList(ExtraKey.EXTRA_CHILDREPAIRTYPELIST);

            //携带维修空间
            ArrayList<CategoryAddBottomBean> extra_spaceList_outSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_SPACELIST);

            if (extra_childRepairTypeList != null && !extra_childRepairTypeList.isEmpty()) {

                if (mDatasTop_childRepairTypeList != null) {
                    mDatasTop_childRepairTypeList.addAll(extra_childRepairTypeList);
                }

            }

            if (extra_spaceList_outSide != null && !extra_spaceList_outSide.isEmpty()) {

                if (mDatasBottom_spaceList != null) {
                    mDatasBottom_spaceList.addAll(extra_spaceList_outSide);
                }

            }

        }

    }

    /**
     * 提交报修拍照或者选择相册之后压缩的目录删除
     */
    private void methodDeleteImageFile() {

        ThreadUtils.executeBySingle(new ThreadUtils.SimpleTask<Void>() {

            @Override
            public Void doInBackground() throws Throwable {

                //判断图片是否压缩成功，我使用的图片是有前缀的 tiny。如果以tiny开头,那么就是压缩成功，提交完毕要删除的。

                //这里仅仅是删除了tiny 文件夹的图片文件。真实拍照的不在此内。
                if (uploadImageListPass != null && !uploadImageListPass.isEmpty()) {

                    for (ImageBean imageBeanItem ://
                            uploadImageListPass) {//

                        //这里删除的是即将上传的信息
                        if (!TextUtils.isEmpty(imageBeanItem.getImageShowPickerUrl())) {

                            String fileNameSure = imageBeanItem.getImageShowPickerUrl().substring(imageBeanItem.getImageShowPickerUrl().lastIndexOf("/") + 1);

                            if (fileNameSure.startsWith(ConstantSign.STARTWITH_TINY_FLAG)) {

                                //删除原始的代码
                                FileUtils.delete(imageBeanItem.getImageShowPickerUrl());

                                //测试代码
                               /*boolean curState =  FileUtils.delete(imageBeanItem.getImageShowPickerUrl());
                               if (curState){
                                   LogUtils.d("itchen----压缩图片删除成功-->"+imageBeanItem.getImageShowPickerUrl());
                                   // itchen----压缩图片删除成功-->/storage/emulated/0/Android/data/com.dgj.propertyred/tiny/tiny-959-2020-08-26-09-42-06.jpg
                               }*/

                            }

                        }
                    }
                }

                //删除files之中的拍照文件===================================================================================
                //删除该文件夹下的 face开头的文件
                //File fileOut = new File(PathUtils.getExternalAppFilesPath() + File.separator + _imagePrefix+TimeUtils.getNowMills() + ".jpg");
                //boolean faceOriginal  = FileUtils.deleteFilesInDirWithFilter(PathUtils.getExternalAppFilesPath(), new FileFilter() {
                FileUtils.deleteFilesInDirWithFilter(PathUtils.getExternalAppFilesPath(), new FileFilter() {

                    @Override
                    public boolean accept(File pathname) {

                        //LogUtils.d("itchen------>pathname-->" + pathname.getAbsolutePath());
                        return pathname.isFile() && pathname.getName().startsWith(ConstantSign.STARTWITH_REPAIR_FLAG);
                    }
                });


                return null;
            }

            @Override
            public void onSuccess(Void result) {

                //LogUtils.d("itchen---->报修部分添加的提交 图片 已经删除完毕");

            }
        });

    }

    /**
     * @author itchenqi QQ:924022142
     * @describe 顶部的维修物品, 特别注意：是单选，只能单选
     */
    class CategoryAddTopAdapter extends BaseQuickAdapter<CategoryAddTopBean, BaseViewHolder> {

        public CategoryAddTopAdapter(int layoutResId, @Nullable List<CategoryAddTopBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, CategoryAddTopBean item) {

            //填充内容
            //String typeName = "测试内容测试测试测试";//item.getTypeName();
            //String imageUrl = "";//item.getImgUrl();

            String typeName = item.getTypeName();
            String imageUrl = item.getImgUrl();

            //顶部文字的选中，为选中变色，做findview。
            TextView textViewCateTop = (TextView) helper.getView(R.id.textviewcatetop);
//          helper.setText(R.id.textviewcatetop, TextUtils.isEmpty(typeName) ? "" : typeName);
            textViewCateTop.setText(TextUtils.isEmpty(typeName) ? "" : typeName);

            //第一种方式,界面刷新频繁创建变量 不明智
            //de.hdodenhof.circleimageview.CircleImageView imageView =
            //(de.hdodenhof.circleimageview.CircleImageView) helper.getView(R.id.imageviewcatetop);

            //第二种方式
            if (item.isChecked()) {

                //文字变色
                textViewCateTop.setTextColor(ColorUtils.getColor(R.color.redcomm));

                //2020年4月9日11:19:58 发现有不是正常链接的情况："imgUrl": "http://222.222.17.184:8881/resource/", 发现有这种类型的
                if (!TextUtils.isEmpty(imageUrl) && !(imageUrl.toLowerCase().endsWith("/"))) {

                    //简略的加载图片内容
                    Glide.with(getContext())//
                            .load(imageUrl.trim())//
                            //.transition(withCrossFade())
                            //.apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .centerInside()//
                            //.placeholder(R.drawable.iconerroryuan)//iconerroryuan
                            //.fallback(R.drawable.iconerroryuan)//iconerroryuan
                            //.error(R.drawable.iconerroryuan)//iconerroryuan
                            .into((ImageView) helper.getView(R.id.imageviewcatetop));


                } else {

                    //LogUtils.d("itchen------>发现了图片 是不正常的图片");

                    //简略的加载图片内容
                    Glide.with(getContext())//
                            .load(imageUrl.trim())//
                            //.transition(withCrossFade())
                            //.apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .centerInside()//
                            .placeholder(R.drawable.iconerroryuan)//iconerroryuan
                            .fallback(R.drawable.iconerroryuan)//iconerroryuan
                            .error(R.drawable.iconerroryuan)//iconerroryuan
                            .into((ImageView) helper.getView(R.id.imageviewcatetop));
                }

                //圈圈内容换成彩色
                /*((de.hdodenhof.circleimageview.CircleImageView)helper.getView(R.id.imageviewcatetop))
                        .setBorderColor(ContextCompat.getColor(mContext,R.color.buttonnomcolor));*/

            } else {

                //文字变色
                textViewCateTop.setTextColor(ColorUtils.getColor(R.color.black));

                if (!TextUtils.isEmpty(imageUrl) && !(imageUrl.toLowerCase().endsWith("/"))) {

                    //简略灰色处理
                    Glide.with(getContext())//
                            .load(imageUrl.trim())//
                            //.transition(withCrossFade())
                            //.apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .centerInside()//
                            .apply(RequestOptions.bitmapTransform(new GrayscaleTransformation()))
                            //.placeholder(R.drawable.iconerroryuan)//iconerroryuan
                            //.fallback(R.drawable.iconerroryuan)//iconerroryuan
                            //.error(R.drawable.iconerroryuan)//iconerroryuan
                            .into((ImageView) helper.getView(R.id.imageviewcatetop));

                } else {

                    //简略灰色处理
                    Glide.with(getContext())//
                            .load(imageUrl.trim())//
                            //.transition(withCrossFade())
                            //.apply(RequestOptions.bitmapTransform(new CircleCrop()))
                            .centerInside()//
                            .apply(RequestOptions.bitmapTransform(new GrayscaleTransformation()))
                            .placeholder(R.drawable.iconerroryuan)//iconerroryuan
                            .fallback(R.drawable.iconerroryuan)//iconerroryuan
                            .error(R.drawable.iconerroryuan)//iconerroryuan
                            .into((ImageView) helper.getView(R.id.imageviewcatetop));

                }

            }
        }
    }

    /**
     * @author itchenqi QQ:924022142
     * @time
     * @describe 底部的物品所属空间
     */
    class CategoryAddBottomAdapter extends BaseQuickAdapter<CategoryAddBottomBean, BaseViewHolder> {

        public CategoryAddBottomAdapter(int layoutResId, @Nullable List<CategoryAddBottomBean> data) {
            super(layoutResId, data);

            addChildClickViewIds(R.id.textviewtagevabottom);

        }

        @Override
        protected void convert(BaseViewHolder helper, CategoryAddBottomBean item) {


            //final String name = "测试测试测测试";//item.getSpaceKind();
            final String name = item.getSpaceKind();

            helper.setText(R.id.textviewtagevabottom, TextUtils.isEmpty(name) ? "" : name);

//            helper.addOnClickListener(R.id.textviewtagevabottom);//整个选项卡均有点击事件内容。。

            //圆角按钮的点击事件内容
            final com.flyco.roundview.RoundTextView textView = helper.getView(R.id.textviewtagevabottom);

            //屏幕高度--->1280-x-720-+-轮播图高度==320 华为手机的
            //做个屏幕判断xiaoy
            if (ScreenUtils.getScreenWidth() <= 720) {
                //LogUtils.d("itchen--11号字体");
                textView.setTextSize(12);
            } else if ((720 < ScreenUtils.getScreenWidth()) && (ScreenUtils.getScreenWidth() <= 1080)) {
                //LogUtils.d("itchen--12号字体");
                textView.setTextSize(13);
            } else if (ScreenUtils.getScreenWidth() > 1080) {
                //LogUtils.d("itchen--13号字体");
                textView.setTextSize(14);
            }


            if (item.isChecked()) {

                //如果是原始状态 没有被选中的状态下那么
                //将来做反色
                textView.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
                textView.getDelegate().setBackgroundColor(ContextCompat.getColor(getContext(), R.color.redcomm));
                textView.getDelegate().setStrokeColor(ContextCompat.getColor(getContext(), R.color.redcomm));
                textView.getDelegate().setBackgroundPressColor(ContextCompat.getColor(getContext(), R.color.redcomm));

            } else {

                //正色是
                textView.setTextColor(ContextCompat.getColor(getContext(), R.color.dark));
                textView.getDelegate().setBackgroundColor(ContextCompat.getColor(getContext(), R.color.white));
                textView.getDelegate().setStrokeColor(ContextCompat.getColor(getContext(), R.color.graybian));
                textView.getDelegate().setBackgroundPressColor(ContextCompat.getColor(getContext(), R.color.graybian));

            }


        }
    }

    /**
     * 初始化时间弹窗的底部弹窗
     */
    private void initTimerPicker() {

        //String beginTime = "2018-10-17 18:00";
        String beginTime = DateFormatUtils.long2Str(System.currentTimeMillis(), true);
        String endTime = "2034-12-12 18:00";//DateFormatUtils.long2Str(System.currentTimeMillis(), true);

        //mTvSelectedTime.setText(endTime);
        // 通过日期字符串初始化日期，格式请用：yyyy-MM-dd HH:mm
        CustomDatePicker mTimerPicker = new CustomDatePicker(this, new CustomDatePicker.Callback() {

            @Override
            public void onTimeSelected(long timestamp) {

                Delivery.getInstance().post(new Runnable() {

                    @Override
                    public void run() {

                        //添加一个时间戳的内容:人为的手动添加 秒，不然的话 是行不通的。
                        //serviceTimeUpload = "2021-10-17 18:00:00";
                        serviceTimeUpload = DateFormatUtils.long2Str(timestamp, true) + ":00";

                        if (textViewHomeTimeInfo != null) {
                            textViewHomeTimeInfo.setText(DateFormatUtils.long2Str(timestamp, true));
                        }
                    }
                });

            }
        }, beginTime, endTime);
        // 允许点击屏幕或物理返回键关闭
        mTimerPicker.setCancelable(true);
        // 显示时和分
        mTimerPicker.setCanShowPreciseTime(true);
        // 允许循环滚动
        mTimerPicker.setScrollLoop(true);
        // 允许滚动动画
        mTimerPicker.setCanShowAnim(true);

        //默认显示当前的时间
        //SimpleDateFormat myFmt2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()

        //第二种格式：
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//等价于now.toLocaleString()

        String curSelectedTime = TimeUtils.getNowString(simpleDateFormat);

        if (mTimerPicker != null) {
            mTimerPicker.show(curSelectedTime);
        }

    }


    private void openMain(int type) {

        if (mGlobalSetting != null) {
            mGlobalSetting = null;
        }

        mGlobalSetting = MultiMediaSetting.from(RepairAddSubmitActivity.this).choose(MimeType.ofImage());

        // 拍摄有关设置
//      CameraSetting cameraSetting = initCameraSetting();

        CameraSetting cameraSetting = new CameraSetting();
        cameraSetting.mimeTypeSet(MimeType.ofImage());

//        相册,仅仅是图片
//        AlbumSetting albumSetting = new AlbumSetting(true)
//                // 支持的类型：图片，视频
//                .mimeTypeSet(MimeType.ofImage())
//                // 是否显示多选图片的数字
//                .countable(true)
//                // 自定义过滤器
//                .addFilter(new GifSizeFilter(320, 320, 5 * BaseFilter.K * BaseFilter.K))
//                // 开启原图
//                .originalEnable(true)
//                // 最大原图size,仅当originalEnable为true的时候才有效
//                .maxOriginalSize(3);

//        mGlobalSetting.albumSetting(albumSetting);
//        mGlobalSetting.cameraSetting(cameraSetting);

        if (type == 1) {

            // 相册,仅仅是图片
            AlbumSetting albumSetting = new AlbumSetting(true)
                    // 支持的类型：图片，视频
                    .mimeTypeSet(MimeType.ofImage())
                    // 是否显示多选图片的数字
                    .countable(true)
                    // 自定义过滤器
                    .addFilter(new GifSizeFilter(320, 320, 5 * BaseFilter.K * BaseFilter.K))
                    // 开启原图
                    .originalEnable(true)
                    // 最大原图size,仅当originalEnable为true的时候才有效
                    .maxOriginalSize(3);

            //开启相册的功能，相册放在左侧
            mGlobalSetting.albumSetting(albumSetting);
            //开启相机的功能。相机在右侧
            mGlobalSetting.cameraSetting(cameraSetting);

        } else if (type == 0) {

            //开启拍摄功能
            mGlobalSetting.cameraSetting(cameraSetting);

        }

        mGlobalSetting
                // 设置路径和7.0保护路径等等
                .allStrategy(new SaveStrategy(true,//
                        ConstantSign.FILE_PROVIDER, //fileProvider
                        ConstantSign.FOLDER_MIDDLELOW))//
                .isImageEdit(false)
                // for glide-V4
                .imageEngine(new Glide4Engine())
                // 最大5张图片、最大3个视频、最大1个音频
                .maxSelectablePerMediaType(null,
                        ConstantApi.MAX_IMAGE_SELECTABLE_PROPERTY_REPAIR,//整体设置；
                        ConstantApi.MAX_VIDEO_SELECTABLE_PROPERTY_REPAIR,//
                        ConstantApi.MAX_AUDIO_SELECTABLE_PROPERTY_REPAIR,//
                        uploadImageListPass.size(),//物业报修最大是3个图片
                        0,
                        0);
//                .forResult(REQUEST_CODE_CHOOSE);
        mGlobalSetting.forResult(new OnResultCallbackListener() {

            @Override
            public void onResult(@NonNull List<? extends LocalFile> result) {

                for (LocalFile localFile : result) {

                    if (localFile != null) {

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult id:" + localFile.getId());
                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 绝对路径:" + localFile.getPath());
                        //args[1] = onResult 绝对路径:/storage/emulated/0/Android/data/com.ygxsk.carhome/files/Pictures/middlelow/IMAGE_20240124_040325966.jpg
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图路径:" + localFile.getOldPath());

//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图路径:" + localFile.getOriginalPath());
                        //args[1] = onResult Uri:content://com.ygxsk.carhome.fileprovider/Pictures/Android/data/com.ygxsk.carhome/files/Pictures/middlelow/IMAGE_20240123_171336391.jpg

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult Uri:" + localFile.getUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图Uri:" + localFile.getOldUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图Uri:" + localFile.getOriginalUri());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 文件大小: " + localFile.getSize());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频音频长度: " + localFile.getDuration());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 是否选择了原图: " + localFile.isOriginal());
//                    if (localFile.isImageOrGif()) {
//                        if (localFile.isImage()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                        } else if (localFile.isImage()) {
//                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                        }
//                    } else if (localFile.isVideo()) {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频类型");
//                    } else if (localFile.isAudio()) {
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 音频类型");
//                    }

//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 具体类型:" + localFile.getMimeType());

                        // 某些手机拍摄没有自带宽高，那么我们可以自己获取
//                        if (localFile.getWidth() == 0 && localFile.isVideo()) {
//                            if (localFile.getPath() != null) {
//                                MediaExtraInfo mediaExtraInfo = MediaUtils.getVideoSize(getApplication(), localFile.getPath());
//                                localFile.setWidth(mediaExtraInfo.getWidth());
//                                localFile.setHeight(mediaExtraInfo.getHeight());
//                                localFile.setDuration(mediaExtraInfo.getDuration());
//                            }
//                        }

//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 宽高: " + localFile.getWidth() + "x" + localFile.getHeight());
//                    LogUtils.d(ConstantSign.LOGCAT_NOMAL + "取出的uri路径=", com.zhongjh.common.utils.UriUtils.uriToFile(getApplicationContext(), localFile.getUri()).getPath());
                        //args[1] = /data/user/0/com.ygxsk.carhome/cache/1706001217800

                        //直接上传？
//                    method_uploadNoHttp(localFile.getPath());

                        if (!TextUtils.isEmpty(localFile.getPath())) {

                            fillImagesLogic(localFile.getPath());

                        } else {
                            ToastUtils.showShort(getResources().getString(R.string.path_image_null));
                        }

                    }

                }

            }

            @Override
            public void onResultFromPreview(@NonNull List<? extends MultiMedia> result, boolean apply) {

                if (apply) {

//                    for (MultiMedia multiMedia : result) {

                    // 绝对路径,AndroidQ如果存在不属于自己App下面的文件夹则无效
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult id:" + multiMedia.getId());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 绝对路径:" + multiMedia.getPath());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图路径:" + multiMedia.getOldPath());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图路径:" + multiMedia.getOriginalPath());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult Uri:" + multiMedia.getUri());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 旧图Uri:" + multiMedia.getOldUri());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 原图Uri:" + multiMedia.getOriginalUri());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 文件大小: " + multiMedia.getSize());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频音频长度: " + multiMedia.getDuration());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 是否选择了原图: " + multiMedia.isOriginal());
//
//                        if (multiMedia.isImageOrGif()) {
//                            if (multiMedia.isImage()) {
//                                LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                            } else if (multiMedia.isImage()) {
//                                LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 图片类型");
//                            }
//                        } else if (multiMedia.isVideo()) {
////                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 视频类型");
//                        } else if (multiMedia.isAudio()) {
////                            LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 音频类型");
//                        }
//
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 具体类型:" + multiMedia.getMimeType());
//                        LogUtils.d(ConstantSign.LOGCAT_NOMAL, "onResult 宽高: " + multiMedia.getWidth() + "x" + multiMedia.getHeight());
//                    }

                }
            }
        });

    }

}